package com.test.simplechat.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author wen
 * channel处理器
 */
public class MyChannelHandler extends ChannelInitializer<SocketChannel> {
    private final static Logger LOGGER = LoggerFactory.getLogger(MyChannelHandler.class);
    private String wsPath;

    public MyChannelHandler(String wsPath) {
        this.wsPath = wsPath;
    }

    public MyChannelHandler() {
    }

    public String getWsPath() {
        return wsPath;
    }

    public void setWsPath(String wsPath) {
        this.wsPath = wsPath;
    }


    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
//        LOGGER.debug("channelId:{} init", channel.id());
        channel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
        channel.pipeline().addLast(new HttpServerCodec());
        channel.pipeline().addLast(new ChunkedWriteHandler());
        channel.pipeline().addLast(new HttpObjectAggregator(8192));
        channel.pipeline().addLast(new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS));
        channel.pipeline().addLast(new HttpRequestHandler(wsPath));
        channel.pipeline().addLast(new WebSocketServerProtocolHandler(wsPath, null, true, 65536 * 10));
        channel.pipeline().addLast(new MyWebSocketHandler(wsPath));
        //存放channel
        ChannelPipeline pl = channel.pipeline();
    }
}
